package com.cwz.controller;

import java.util.*;

public class RecommendationEngine {

    // 用户-帖子交互数据
    private Map<Integer, Set<Integer>> userPostsMap = new HashMap<>();

    public RecommendationEngine() {
        // 初始化用户-帖子交互数据
        userPostsMap.put(1, new HashSet<>(Arrays.asList(101, 102)));
        userPostsMap.put(2, new HashSet<>(Arrays.asList(101, 103)));
        userPostsMap.put(3, new HashSet<>(Arrays.asList(102, 103)));
    }

    // 计算两个用户之间的余弦相似度
    public double cosineSimilarity(Set<Integer> user1, Set<Integer> user2) {
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (Integer post : user1) {
            dotProduct += Collections.frequency(user2, post);
            normA++;
        }

        for (Integer post : user2) {
            normB++;
        }

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }

    // 获取推荐帖子
    public List<Integer> recommendPosts(int userID, int numRecommendations) {
        List<Map.Entry<Integer, Double>> similarUsers = new ArrayList<>();
        Map<Integer, Double> scores = new HashMap<>();

        for (Map.Entry<Integer, Set<Integer>> entry : userPostsMap.entrySet()) {
            if (entry.getKey() != userID) {
                double similarity = cosineSimilarity(userPostsMap.get(userID), entry.getValue());
                similarUsers.add(new AbstractMap.SimpleEntry<>(entry.getKey(), similarity));
            }
        }

        // 按相似度排序
        similarUsers.sort((u1, u2) -> u2.getValue().compareTo(u1.getValue()));

        Set<Integer> recommendedPosts = new HashSet<>();

        for (int i = 0; i < similarUsers.size() && recommendedPosts.size() < numRecommendations; i++) {
            Integer similarUserID = similarUsers.get(i).getKey();
            for (Integer post : userPostsMap.get(similarUserID)) {
                if (!userPostsMap.get(userID).contains(post)) {
                    scores.put(post, scores.getOrDefault(post, 0.0) + similarUsers.get(i).getValue());
                    recommendedPosts.add(post);
                }
            }
        }

        // 按分数排序获取推荐结果
        List<Integer> sortedRecommendedPosts = new ArrayList<>(scores.keySet());
        sortedRecommendedPosts.sort((p1, p2) -> scores.get(p2).compareTo(scores.get(p1)));

        return sortedRecommendedPosts.subList(0, numRecommendations);
    }

    public static void main(String[] args) {
        RecommendationEngine engine = new RecommendationEngine();
        List<Integer> recommendedPosts = engine.recommendPosts(2, 1);
        System.out.println("Recommended posts for user 2: " + recommendedPosts);
    }
}